<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-cell-group inset border>
        <van-field v-model="form.username" name="用户名" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="form.password" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 登录 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import type { ILoginQuery } from '@/api';
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { loginApi } from '../api/index';
import { showFailToast } from 'vant';
import 'vant/lib/toast/index.css';

const route = useRoute();
const router = useRouter();

const form = reactive<ILoginQuery>({
  username: 'admin',
  password: '123456',
});

const onSubmit = () => {
  loginApi(form)
    .then((res) => {
      localStorage.setItem('token', res);
      router.replace((route.query.redirect as string) ?? '/');
    })
    .catch((err) => {
      showFailToast(err);
    });
};
</script>

<style lang="scss" scoped>
.login {
  height: calc(100vh - 50px);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
